package org.guage.process.task.schedule;

import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

/**
 * @author 杨得朝
 * @since 1.1.1
 */
public class JvmLoggerTask implements SchedulingConfigurer {

	private final static Logger log = LoggerFactory.getLogger(JvmLoggerTask.class);
	/**
	 * dbpool日志开关
	 */
	@Value(value = "${application.log.process.enable:true}")
	private Boolean isSwitch;
	/**
	 * jvm周期cron表达式
	 */
	@Value(value = "${application.log.process.collectFreq:0/5 * * * * ?}")
	private String cron;

	@Override
	public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
		log.debug("jvm开关isSwitch=" + isSwitch);
		if (isSwitch) {
			scheduledTaskRegistrar.addTriggerTask(
					// Perform scheduled tasks
					() -> {
						try {
							writeLog();
						} catch (Exception e) {
							log.error("writeLog", e);
						}
					},
					// set trigger
					triggerContext -> {
						// Initialize scheduled task cycle

						if (StringUtils.isEmpty(cron)) {
							cron = getCron();
						}
						CronTrigger trigger = new CronTrigger(cron);
						return trigger.nextExecutionTime(triggerContext);
					});
		}

	}

	/**
	 * 获取操作系统信息
	 * 
	 * @param operatingSystem
	 * @param methodName
	 * @return
	 */
	private static long getLongFromOperatingSystem(OperatingSystemMXBean operatingSystem, String methodName) {
		try {
			final Method method = operatingSystem.getClass().getMethod(methodName, (Class<?>[]) null);
			method.setAccessible(true);
			return (Long) method.invoke(operatingSystem, (Object[]) null);
		} catch (final InvocationTargetException e) {
			if (e.getCause() instanceof Error) {
				throw (Error) e.getCause();
			} else if (e.getCause() instanceof RuntimeException) {
				throw (RuntimeException) e.getCause();
			}
			throw new IllegalStateException(e.getCause());
		} catch (final NoSuchMethodException e) {
			throw new IllegalArgumentException(e);
		} catch (final IllegalAccessException e) {
			throw new IllegalStateException(e);
		}
	}

	/**
	 * 获取周期表达式
	 */
	protected String getCron() {
		return cron;
	}

	public void writeLog() {
		System.out.println("sdfasdfasdfasdf");
	}

}
